package org.example.controller;

import org.example.model.DataSourceConfig;
import org.example.service.DataSourceConfigService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author by PengHongChao
 * @date 2025/7/7 10:32
 */
@RestController
@RequestMapping("/api/datasources")
public class DataSourceController {
    private final DataSourceConfigService configService;

    public DataSourceController(DataSourceConfigService configService) {
        this.configService = configService;
    }

    @PostMapping
    public ResponseEntity<?> create(@RequestBody DataSourceConfig config) {
        configService.createDataSource(config);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> update(@PathVariable Long id,
                                    @RequestBody DataSourceConfig config) {
        config.setId(id);
        configService.updateDataSource(config);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        configService.deleteDataSource(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}/test")
    public ResponseEntity<Boolean> testConnection(@PathVariable Long id) {
        DataSourceConfig config = configService.getById(id);
        return ResponseEntity.ok(configService.testConnection(config));
    }

    @GetMapping
    public ResponseEntity<List<DataSourceConfig>> listAll() {
        return ResponseEntity.ok(configService.listAll());
    }
}
